package cn.fl.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.user.facade.system.api.IPriorityApiService;
import cmm.user.facade.system.condition.SysResourceQueryCondition;
import cmm.user.facade.system.constant.SysResourceConstant;
import cmm.user.facade.system.dto.SysResourceDTO;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.service.ISysResourceService;
import cn.fl.system.transform.SysResourceVOTransform;
import cn.fl.system.vo.SysResourceVO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class SysResourceServiceImpl implements ISysResourceService {

	/**
	 * 日志
	 */
	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(SysResourceServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IPriorityApiService priorityApiService;
	
	/**
	 * 本地数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;

	@Override
	public SysResourceVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,BaseExceptionConstant.BASE_EXCEPTION_CODE_600_NAME);
		}
		SysResourceDTO dto = priorityApiService.selectSysResourceById(id);
		SysResourceVO sysResourceVO = SysResourceVOTransform.toVO(dto);
		this.setSysResourceVOWithDicInfo(sysResourceVO, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		return sysResourceVO;
	}
	/**
	 * 设置系统资源中关于字典项信息
	 * @param SysFlCompInfoDTO
	 */
	private void setSysResourceVOWithDicInfo(SysResourceVO sysResourceVO,String sysCd,String orgCd) {
		if(null == sysResourceVO){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_601, BaseExceptionConstant.BASE_EXCEPTION_CODE_601_NAME);
		}
		if(StringUtils.isNotEmpty(sysResourceVO.getIsValid())){
			SysDictionaryDTO isValidCdObj = this.sysDictionaryApiService.getCode(sysCd, orgCd, DictionaryConstant.CODE_GRP_IS_VALID_CD, sysResourceVO.getIsValid().toString());
			if(null !=isValidCdObj){
				sysResourceVO.setIsValidNm(isValidCdObj.getCodeNm());
			}
		}
		if(StringUtils.isNotEmpty(sysResourceVO.getResTypCd())){
			SysDictionaryDTO resTypCdObj = this.sysDictionaryApiService.getCode(sysCd, orgCd, DictionaryConstant.CODE_GRP_SYS_RES_TYP_CD, sysResourceVO.getResTypCd());
			if(null !=resTypCdObj){
				sysResourceVO.setResTypCdNm(resTypCdObj.getCodeNm());
			}
		}
		
	}

	@Override
	public JSONArray searchTreeInit() throws BaseException {
		JSONArray jsonArray = new JSONArray ();
		List<SysResourceDTO> sysResInitList = this.priorityApiService.searchSysResourceByPid(SysResourceConstant.SYS_RES_CD_PID_INIT,CurrentThreadContext.getCurrentSysCd());
		JSONArray jsonArrayRes = setValueToArrayInit(sysResInitList, jsonArray);
		
		return jsonArrayRes;
	}
	@Override
	public JSONArray searchTreeIsCheckById(List<Long> ids) throws BaseException {
		JSONArray jsonArray = new JSONArray ();
		List<SysResourceDTO> sysResInitList = this.priorityApiService.searchSysResourceByPid(SysResourceConstant.SYS_RES_CD_PID_INIT,CurrentThreadContext.getCurrentSysCd());
		JSONArray jsonArrayRes = setValueToArray(sysResInitList, jsonArray,ids);
		
		return jsonArrayRes;
	}

	/**
	 * 初始化递归添加方法
	 */
	private JSONArray setValueToArrayInit(List<SysResourceDTO> list,JSONArray array){
		
		if(CollectionUtils.isNotEmpty(list)){
			for (SysResourceDTO sysResourceDTO : list) {
				  Long id = sysResourceDTO.getId();
				  JSONObject jsonObject = new JSONObject ();
				  jsonObject.put("id",id );
				  jsonObject.put("text",sysResourceDTO.getResNm());
				  if(StringUtils.isNotEmpty(sysResourceDTO.getResImg())){
					  jsonObject.put("iconClass", sysResourceDTO.getResImg());
				  }
				  List<SysResourceDTO> childrenList = this.priorityApiService.searchSysResourceByPid(id,CurrentThreadContext.getCurrentSysCd());
				  if(CollectionUtils.isNotEmpty(childrenList)){
					  JSONArray jsonArray2 = setValueToArrayInit(childrenList, new JSONArray());
					  jsonObject.put("children",jsonArray2);
				  }
				  array.add(jsonObject);
				  
			}
		}
		return array;
	}
	
	/**
	 * 关联递归添加方法
	 */
	private JSONArray setValueToArray(List<SysResourceDTO> list,JSONArray array,List<Long> resrList){
		
		if(CollectionUtils.isNotEmpty(list)){
			for (SysResourceDTO sysResourceDTO : list) {
				Long id = sysResourceDTO.getId();
				JSONObject jsonObject = new JSONObject ();
				if(CollectionUtils.isNotEmpty(resrList)&&resrList.contains(id)){
					jsonObject.put("ischecked", true);
				}else{
					jsonObject.put("ischecked", false);
				}
				jsonObject.put("id",id );
				jsonObject.put("text",sysResourceDTO.getResNm());
				if(StringUtils.isNotEmpty(sysResourceDTO.getResImg())){
					  jsonObject.put("iconClass", sysResourceDTO.getResImg());
				}
				List<SysResourceDTO> childrenList = this.priorityApiService.searchSysResourceByPid(id,CurrentThreadContext.getCurrentSysCd());
				if(CollectionUtils.isNotEmpty(childrenList)){
					JSONArray jsonArray2 = setValueToArray(childrenList, new JSONArray(),resrList);
					jsonObject.put("children",jsonArray2);
				}
				array.add(jsonObject);
				
			}
		}
		return array;
	}
	
	/**
	 * 根据条件模糊查询树
	 */
	@Override
	public JSONArray searchResRTree(List<Long> ids ,SysResourceQueryCondition condition) throws BaseException {
		if(condition==null){
			JSONArray jsonArray = this.searchTreeIsCheckById(ids);
			return jsonArray;
		}
		List<SysResourceDTO> searchResRListByResNm = this.priorityApiService.searchResRListByResNm(condition);
		if(CollectionUtils.isEmpty(searchResRListByResNm)){
			return new JSONArray();
		}
		
		JSONArray jsonArray = new JSONArray();
		for (SysResourceDTO sysResourceDTO : searchResRListByResNm) {
			JSONObject obj = new JSONObject();
			Long id = sysResourceDTO.getId();
			if(CollectionUtils.isNotEmpty(ids)&&ids.contains(id)){
				obj.put("ischecked", true);
			}else{
				obj.put("ischecked", false);
			}
			obj.put("id", sysResourceDTO.getId());
			obj.put("text", sysResourceDTO.getResNm());
			obj.put("pid", sysResourceDTO.getResPid());
			if(StringUtils.isNotEmpty(sysResourceDTO.getResImg())){
				obj.put("iconClass", sysResourceDTO.getResImg());
			}else{
				obj.put("iconClass", "");
			}
			
			jsonArray.add(obj);
		}
		JSONArray treeMenuList = treeMenuList(jsonArray,SysResourceConstant.SYS_RES_CD_PID_INIT);
		return treeMenuList;
	}
	/**
	 * 递归添加整个集合数据
	 * @param treeList
	 * @param parentId
	 * @return
	 */
	public JSONArray treeMenuList(JSONArray treeList, Long parentId) {  
	       JSONArray childMenu = new JSONArray();  
	       for (Object object : treeList) {  
	           JSONObject jsonMenu = JSONObject.fromObject(object);  
	           long oid = jsonMenu.getLong("id"); 
	           long pid = jsonMenu.getLong("pid"); 
	           if (parentId == pid) {  
	               JSONArray c_node = treeMenuList(treeList, oid);  
	               jsonMenu.put("children", c_node); 
	               childMenu.add(jsonMenu);  
	           }  
	       }  
	       return childMenu;  
	   }

	@Override
	public List<SysResourceDTO> searchMenuWithAuthTree(String sysCd, Long roleId) throws BaseException {
		List<SysResourceDTO> tree = new ArrayList<>();
		if(StringUtils.isBlank(sysCd) || StringUtils.isEmpty(roleId)){
			return tree;
		}
		List<SysResourceDTO> list =  this.priorityApiService.searchMenuWithAuthList(sysCd, roleId);
		if(CollectionUtils.isEmpty(list))return tree;
		tree = this.getMenuTree(list, SysResourceConstant.SYS_RES_CD_PID_INIT);
		return tree;
	}  
	
	/**
	 * 
	 * @param list
	 * @param pid
	 * @return
	 */
	private List<SysResourceDTO> getMenuTree(List<SysResourceDTO> list, Long pid){
		List<SysResourceDTO> tree = new ArrayList<>();
		for (SysResourceDTO sysResourceDTO : list) {
			if(sysResourceDTO.getResPid().equals(pid)){
				List<SysResourceDTO> childTree = this.getMenuTree(list, sysResourceDTO.getId());
				sysResourceDTO.setChildList(childTree);
				tree.add(sysResourceDTO);
			}
		}
		return tree;
	}

	@Override
	public Boolean searchFuncWithAuth(String sysCd, Long roleId, String resCd) throws BaseException {
		Boolean pass = false;
		if(StringUtils.isBlank(sysCd) || StringUtils.isEmpty(roleId) || StringUtils.isEmpty(resCd)){
			return pass;
		}
		List<SysResourceDTO> list =  this.priorityApiService.searchFuncWithAuth(sysCd, roleId, resCd);
		if(CollectionUtils.isEmpty(list)){
			return pass;
		}
		pass = true;
		return pass;
	}
	@Override
	public Boolean searchResourceWithAuth(String sysCd, Long roleId, String resCd) throws BaseException {
		Boolean pass = false;
		if(StringUtils.isBlank(sysCd) || StringUtils.isEmpty(roleId) || StringUtils.isEmpty(resCd)){
			return pass;
		}
		List<SysResourceDTO> list =  this.priorityApiService.searchResourceWithAuth(sysCd, roleId, resCd, null);
		if(CollectionUtils.isEmpty(list)){
			return pass;
		}
		pass = true;
		return pass;
	}
}
